<?php


namespace app\manage\controller;

use think\Db;
use think\Log;
use app\common\model\StatCity;
use app\common\model\PushRecord;
use think\Queue;

class Push extends Base
{
    public function _initialize()
    {
        parent::_initialize();
    }

    public function index()
    {
        $pro_name = input('pro_name', '');
        $mer_name = input('mer_name', '');
        $status = input('status', '');
        $cityname = input('cityname', '');
        $channel_id = input('channel_id/a', 0);
        $orderb = input('orderb', 0);
        $account_id = input('account_id/a', 0);
        $type = input('type', 2);
        $realname = input('realname', '');
        $mobile = input('mobile', '');

        $map = [];
        $mapa = [];
        if ($pro_name != '') {
            $products = Db::name('product')->field('id')->where(['name' => ['like', '%' . $pro_name . '%']])->select();
            $pro_id_list = array_column($products, 'id');
            $map['a.pro_id'] = ['in', $pro_id_list];
        }

        if ($status != 0) {
            $map['a.status'] = $status;
        }

        //模糊查询城市
        if (!empty($cityname)) {
            $cityIdArr = Db::name('city')->field('id,type,pid')->where('name', 'like', $cityname . "%")->where('type', 2)->find();
            if ($cityIdArr) {
                $map['a.city'] = $cityIdArr['pid'] . '-' . $cityIdArr['id'];
            } else {
                $map['a.city'] = 0;
            }
        }

        if ($type == 1) {
            $map['type'] = $type;
            if (!empty($channel_id)) {
                if (count($channel_id) == 1 && $channel_id[0] == 0) {

                } else {
//                $map['a.channel_id']=['in',$channel_id];

                    $channelStr = [];
                    foreach ($channel_id as $v) {
                        $channelStr[] = 'find_in_set("' . $v . '",channel_id)';
                    }
                    $mapa = implode(' or ', $channelStr);

                }
            }
        } elseif ($type == 2) {
            $map['type'] = $type;
            if (!empty($account_id)) {
                if (count($account_id) == 1 && $account_id[0] == 0) {

                } else {
//                $map['a.channel_id']=['in',$channel_id];

                    $channelStr = [];
                    foreach ($account_id as $v) {
                        $channelStr[] = 'find_in_set("' . $v . '",account_id)';
                    }
                    $mapa = implode(' or ', $channelStr);

                }
            }
        }

        if (!empty($mobile) || !empty($mer_name)) {
            if (in_array($this->group_id, [4, 5])) {
                $map1['bind_aid|weihu_aid'] = $this->uid;
            }
            if (!empty($mobile)) {
                $map1['phone'] = ['like', '%' . $mobile . '%'];
            }
            if (!empty($mer_name)) {
                $map1['mer_name'] = ['like', '%' . $mer_name . '%'];
            }
            $mArr = model('merchant')->where($map1)->column('id');
            if (!empty($mArr)) {
                $map['mer_id'] = ['in', $mArr];
            } else {
                $map['mer_id'] = 0;
            }
        }

        if (!empty($realname)) {
            $map['c.realname'] = $realname;
        }

        $orderBy = 'a.id desc';
        if ($orderb == 1) {
            $orderBy = 'balance asc';
        } elseif ($orderb == 2) {
            $orderBy = 'balance desc';
        } elseif ($orderb == 3) {
            $orderBy = 'update_time asc';
        } elseif ($orderb == 4) {
            $orderBy = 'update_time desc';
        }

        $productArr = Db::name('product')->column('name', 'id');
        $ChannelArr = model('Channel')->column('name', 'id');

        $accountAll = Db::name('Account')->column('acc_name', 'id');

//        $infos = model('Push')->getInfosByMap($map, '', false);
        $infos = model('Push')->alias('a')->field('a.*,b.mer_name,b.mer_desc,b.username,b.phone,balance,c.realname')
            ->join('merchant b', 'b.id=a.mer_id')
            ->join('admin c', 'c.id=b.weihu_aid','LEFT')
            ->where($map)
            ->where($mapa)
            ->order($orderBy)->paginate();
        foreach ($infos as $k => $v) {
            if ($v['type'] == 1) {
                $infos[$k]['type_name'] = '渠道';
            } elseif ($v['type'] == 2) {
                $infos[$k]['type_name'] = '账户';
            } else {
                $infos[$k]['type_name'] = '全部';
            }

            $infos[$k]['pro_name'] = $productArr[$v['pro_id']];
//            $mer = Db::name('merchant')->field('mer_name,mer_desc,username,phone,delete_time')->where(['id'=>$v['mer_id']])->find();
//            $infos[$k]['mer_name'] = $mer['mer_name'] ?? '';
//            $infos[$k]['mer_desc'] = $mer['mer_desc'] ?? '';
//            $infos[$k]['username'] = $mer['username'] ?? '';
//            $infos[$k]['is_delete'] = $mer['delete_time'] ?? '';
//            $infos[$k]['phone'] = $mer['phone'] ?? '';
            if (empty($v['channel_id'])) {
                $infos[$k]['channel_name'] = '全部渠道';
            } else {
                $channel = explode(',', $v['channel_id']);
                $channelStr = [];
                foreach ($channel as $vv) {
                    $channelStr[] = $ChannelArr[$vv];
                }
                $infos[$k]['channel_name'] = implode('<br>', $channelStr);
            }

            if (empty($v['account_id'])) {
                $infos[$k]['account_name'] = '全部账户';
            } else {
                $channel = explode(',', $v['account_id']);
                $channelStr = [];
                foreach ($channel as $vv) {
                    $channelStr[] = $accountAll[$vv];
                }
                $infos[$k]['account_name'] = implode('<br>', $channelStr);
            }

            if ($v['city'] != '') {
                $ids = explode('-', $v['city']);
                $prov = $this->getCityName($ids[0]);
                $city = $this->getCityName($ids[1]);
                if ($prov == $city) {
                    $infos[$k]['city'] = $prov;
                } else {
                    $infos[$k]['city'] = $prov . '-' . $city;
                }
            }
            if ($v['charge_type'] == 1) {
                $infos[$k]['charge_type'] = '按服务收费';
                $infos[$k]['price'] = '--';
            } else {
                $infos[$k]['charge_type'] = '按单价收费';
                $infos[$k]['price'] = $v['price'] . '元';
            }
            $weekArr = [];
            if (!empty($v['week_time'])) {
                $weekTime = json_decode($v['week_time']);
                foreach ($weekTime as $key => $val) {
                    if ($key == 10) {
//                        $v['week_arr'][]=['name'=>'全部','time'=>$val];
                        $weekArr[] = "全部：" . $val;
                    } elseif ($key == 1) {
                        $weekArr[] = "星期一：" . $val;
//                        $v['week_arr'][]=['name'=>'星期一','time'=>$val];
                    } elseif ($key == 2) {
                        $weekArr[] = "星期二：" . $val;
//                        $v['week_arr'][]=['name'=>'星期二','time'=>$val];
                    } elseif ($key == 3) {
                        $weekArr[] = "星期三：" . $val;
//                        $v['week_arr'][]=['name'=>'星期三','time'=>$val];
                    } elseif ($key == 4) {
                        $weekArr[] = "星期四：" . $val;
//                        $v['week_arr'][]=['name'=>'星期四','time'=>$val];
                    } elseif ($key == 5) {
                        $weekArr[] = "星期五：" . $val;
//                        $v['week_arr'][]=['name'=>'星期五','time'=>$val];
                    } elseif ($key == 6) {
                        $weekArr[] = "星期六：" . $val;
//                        $v['week_arr'][]=['name'=>'星期六','time'=>$val];
                    } elseif ($key == 0) {
                        $weekArr[] = "星期日：" . $val;
//                        $v['week_arr'][]=['name'=>'星期日','time'=>$val];
                    }
                }
            }
            $infos[$k]['week_arr'] = implode('<br>', $weekArr);

            // 手机MD5包
            if (empty($v['mobile_pack_id'])) {
                $infos[$k]['mobile_pack'] = '';
            } else {
                $mobile_pack_arr = \db('mobile_pack')->column('title','id');
                $mobile_pack_ids = explode(',', $v['mobile_pack_id']);
                $str = [];
                foreach ($mobile_pack_ids as $vv) {
                    if (!empty($mobile_pack_arr[$vv])) {
                        $str[] = $mobile_pack_arr[$vv];
                    }

                }
                $infos[$k]['mobile_pack'] = implode('<br>', $str);
            }
        }

        $province = Db::name('city')->where(['pid' => 1])->select();
        $products = model('Product')->getListByMap();
        $merchants = model('Merchant')->getListByMap([], '', '', false);

        if (is_array($channel_id)) {
            $channel_id = implode(',', $channel_id);
        } else {
            $channel_id = 0;
        }

        if (is_array($account_id)) {
            $account_id = implode(',', $account_id);
        } else {
            $account_id = 0;
        }

        $account = model('Account')->getListByMap([], 'id,acc_name,channel_id');


        $accountTree = [];
        foreach ($ChannelArr as $k => $v) {
            $temp['id'] = $k;
            $temp['name'] = $v;
            $temp['sub'] = [];
            foreach ($account as $key => $val) {
                if ($val['channel_id'] == $k) {
                    $temp['sub'][] = ['id' => $val['id'], 'name' => $val['acc_name']];
                }
            }
            $accountTree[] = $temp;
        }

        $mobile_pack_array = \db('mobile_pack')->where(['status'=>1])->select();

        return $this->fetch('', [
            'infos' => $infos,
            'pro_name' => $pro_name,
            'mer_name' => $mer_name,
            'status' => $status,
            'province' => $province,
            'products' => $products,
            'merchants' => $merchants,
            'channel' => $ChannelArr,
            'group_id' => $this->group_id,
            'cityname' => $cityname,
            'channel_id' => $channel_id,
            'orderb' => $orderb,
            'account_id' => $account_id,
            'account' => $account,
            'type' => $type,
            'accountTree' => $accountTree,
            'realname' => $realname,
            'mobile_pack_array' => $mobile_pack_array,
            'mobile' => $mobile,
        ]);
    }


    public function edit()
    {
        $id = input('id');
        if (!$id) return self::showReturnCode(1002, 'id 错误');
        $info = model('Push')->getInfoByMap(['id' => $id]);
        if ($info['city'] != 0) {
            $ids = explode('-', $info['city']);
            $info['prov'] = $ids[0];
            $info['city'] = $ids[1];
            $info['city_name'] = $this->getCityName($ids[1]);
        } else {
            $info['prov'] = 0;
            $info['city'] = 0;
            $info['city_name'] = '';
        }
        $info['week_json'] = $info['week_time'];
        if (empty($info['week_time'])) {
            $info['week_time'] = 10;
        } else {
            $info['week_time'] = implode(',', array_keys(json_decode($info['week_time'], true)));
        }
        return self::showJsonReturnCodeData('1001', $info, '');
    }

    public function save()
    {
        if (request()->isAjax()) {
            try {

                $id = input('post.id');
                $save_data = input('post.');
                $save_data['type'] = 2;

                if ($save_data['type'] == 1) {
                    if (!isset($save_data['channel_id'])) {
                        return self::showReturnCode(1011, '请选择渠道');
                    }
                } elseif ($save_data['type'] == 2) {
                    if (!isset($save_data['account_id'])) {
                        return self::showReturnCode(1011, '请选择账户');
                    }
                } else {
                    return self::showReturnCode(1011, '请选择投放维度');
                }


                $cityId = $save_data['city'];
                if ($save_data['province'] != '') {
                    $save_data['city'] = $save_data['province'] . '-' . $save_data['city'];
                } else {
                    $save_data['city'] = '';
                }

                if (isset($save_data['charge_type']) && $save_data['charge_type'] == 1) {
                    $save_data['price'] = 0;
                }

                if (isset($id) && $id) {
                    $save_data['id'] = $id;

                    $push = Db::name('push')->where('id', $id)->find();

                    if (empty($save_data['is_pro_price']) && $push['charge_type'] == 2) {
                        $city = Db::name('city')->where(['id' => $cityId, 'type' => 2])->find();
                        $pro_price = json_decode($city['pro_price'], true);
                        if (!empty($pro_price)) {
                            $pprice = isset($pro_price[$save_data['pro_id']]) ? $pro_price[$save_data['pro_id']] : 0;
                            if (!empty($pprice)) {
                                if ($save_data['price'] < $pprice) {
                                    return self::showReturnCode(3011, '单价小于' . $pprice . '的指导价，还需要继续设置吗？');
                                }
                            }
                        }
                    }

                } else {

                    $save_data['status'] = 1;
                    unset($save_data['id']);

                    if (empty($save_data['is_pro_price']) && $save_data['charge_type'] == 2) {
                        $city = Db::name('city')->where(['id' => $cityId, 'type' => 2])->find();
                        $pro_price = json_decode($city['pro_price'], true);
                        if (!empty($pro_price)) {
                            $pprice = isset($pro_price[$save_data['pro_id']]) ? $pro_price[$save_data['pro_id']] : 0;
                            if (!empty($pprice)) {
                                if ($save_data['price'] < $pprice) {
                                    return self::showReturnCode(3011, '单价小于' . $pprice . '的指导价，还需要继续设置吗？');
                                }
                            }
                        }
                    }
                }

                $save_data['channel_type'] = '';
                if ($save_data['type'] == 1) {
                    if (in_array(0, $save_data['channel_id'])) {
                        $save_data['channel_id'] = 0;
                    } else {
                        if (count($save_data['channel_id']) == 1) {
                            $save_data['channel_id'] = $save_data['channel_id'][0];
                        } else {
                            $save_data['channel_id'] = implode(',', $save_data['channel_id']);
                        }
                    }
                } elseif ($save_data['type'] == 2) {
                    if (in_array(0, $save_data['account_id'])) {
                        $save_data['account_id'] = 0;
                        $save_data['channel_type'] = 0;
                    } else {
                        // 需要构建channel_type字段：渠道id字符传
                        // 设置push表的 channel_type字段 渠道id字符传 判断是否包含渠道内所有的账户
                        $channel = \db('channel')->field('id')->where('status', 1)->select();
                        $account = \db('account')->field('channel_id,id')->where('status', 1)->select();
                        foreach ($channel as &$channel_v) {
                            $channel_v['accounts'] = [];
                            foreach ($account as &$acc_v) {
                                if ($channel_v['id'] == $acc_v['channel_id']) {
                                    $channel_v['accounts'][] = $acc_v['id'];
                                }
                            }
                            unset($acc_v);
                        }
                        unset($channel_v);
                        $channel_type = $update = [];
                        foreach ($channel as $channel_acc) {
                            $intersect = array_intersect($save_data['account_id'], $channel_acc['accounts']);
                            if (array_values($channel_acc['accounts']) == array_values($intersect) && !empty($channel_acc['accounts'])) {
                                $channel_type[] = $channel_acc['id'];
                            }
                        }
                        $save_data['channel_type'] = !empty($channel_type) ? implode(",", $channel_type) : "";

                        $save_data['account_id'] = implode(',', $save_data['account_id']);
                    }
                }

                $endWeek = [];
                if (!empty($save_data['week_time'])) {
                    foreach ($save_data['week_time'] as $v) {
                        if ($v == 10) {
                            $endWeek = [];
                            $wArr = explode(' - ', $save_data['weekday'][$v]);
                            if (count($wArr) == 2) {
                                if ($wArr[0] != $wArr[1]) {
                                    $endWeek[$v] = $save_data['weekday'][$v];
                                } else {
                                    $endWeek[$v] = '';
                                }
                            } else {
                                $endWeek[$v] = $save_data['weekday'][$v];
                            }
                            break;
                        } else {
                            $wArr = explode(' - ', $save_data['weekday'][$v]);
                            if (count($wArr) == 2) {
                                if ($wArr[0] != $wArr[1]) {
                                    $endWeek[$v] = $save_data['weekday'][$v];
                                } else {
                                    $endWeek[$v] = '';
                                }
                            } else {
                                $endWeek[$v] = $save_data['weekday'][$v];
                            }
                        }
                    }
                }

                $save_data['week_time'] = json_encode($endWeek);
                $endWeekArr = array_keys($endWeek);
                $endWeekDay = [];
                foreach ($endWeekArr as $v) {
                    if ($v != 10) {
                        $endWeekDay[] = $v;
                    }
                }

                $save_data['week_day'] = implode(',', $endWeekDay);

                if (!empty($save_data['timing_time'])) {
                    $timing_time = explode(' - ', $save_data['timing_time']);
                    $save_data['start_time'] = $timing_time[0];
                    $save_data['end_time'] = $timing_time[1];
                }

                if (!empty($save_data['mobile_pack_id'])) {
                    $save_data['mobile_pack_id'] = implode(',', $save_data['mobile_pack_id']);
                }

                $result = $this->editData(false, '', 'Push', $save_data);
                $statcityModel = new StatCity();
                $push_record_model = new PushRecord();
                if ($result['code'] == 1001) {
                    if (isset($id) && $id) {
                        // 统计 城市需求满足率
                        $push_new = model('Push')->where('id', $id)->find();
                        $statcityModel->modifyByEditPush($push, $push_new);

                        // 判断每日规则记录
                        $push_record_model->editPushToRecord($push_new);

                        $result['msg'] = '修改分发规则成功';
                        $this->RecordSystemLog($this->uid, $this->behavior, '修改分发规则成功');
                    } else {
                        $statcityModel->modifyByAddPush($save_data);

                        // 判断每日规则记录
                        $push = $save_data;
                        $push['id'] = $result['id'];
                        $push_record_model->addPushToRecord($push);

                        $result['msg'] = '添加分发规则成功';
                        $this->RecordSystemLog($this->uid, $this->behavior, '添加分发规则成功');
                    }

                    $mer = \db('merchant')->find($save_data['mer_id']);
                    /*if ($mer['status'] != 1) {
                        return $this->showReturnCode(399, '检查到商户未启用是否确认启用？');
                    }*/
                }

                return $result;
            } catch (\Exception $e) {
                Log::error($e->getMessage());
                return self::showReturnCode(1011, $e->getMessage());
            }
        } else {
            return self::showReturnCode(1002);
        }
    }

    public function status()
    {
        if ($this->request->isAjax()) {
            $id = input('post.id');

            $push = model('Push')->where('id', $id)->find();

            $res = model('Push')->save(['status' => input('post.status')], ['id' => $id]);
            if ($res) {
                // 重新统计城市需求满足率数据
                $statcityModel = new StatCity();
                $statcityModel->modifyByStatusPush($push);

                $this->RecordSystemLog($this->uid, $this->behavior, '状态操作成功,操作ID: ' . $id);

                if (input('post.status') == 1) {

                    // 判断每日规则记录
                    $push_record_model = new PushRecord();
                    $push['status'] = 1;
                    $push_record_model->editPushToRecord($push);

                    $mer_id = $push['mer_id'];
                    $mer = Db::name('merchant')->find($mer_id);
                    if ($push['timing_time'] == '') {
                        return $this->showReturnCode(1011, '请先设置定时投放时间');
                    }
                    /*if ($mer['status'] != 1) {
                        return $this->showReturnCode(399, '检查到商户未启用是否确认启用？');
                    }*/
                }

                return $this->showReturnCode(1001);
            } else {
                return $this->showReturnCode(1009, '操作失败');
            }
        } else {
            return $this->showReturnCode(1002);
        }
    }

    /**
     * 软删除
     */
    public function delete()
    {
        if($this->request->isAjax()){
            $id = input('post.id');
            $model = $this->request->controller();
            $infoTemp = model($model)->getInfoByMap('','','',false);
            if(isset($infoTemp['parent_id'])){
                $infosCount = model($model)->countNum(['parent_id'=>$id],false); // 查询子分类数量
                if($infosCount > 0)  return $this->showReturnCode(1009,'该分类下有子分类,请批量删除');
            }
            $push = model('Push')->where('id', $id)->find();
            $res = model($model)->destroy($id);
            if($res){
                // 重新统计城市需求满足率数据
                $statcityModel = new StatCity();
                $statcityModel->modifyByDelPush($push);

                $this->RecordSystemLog($this->uid,$this->behavior,'删除成功,操作ID: '.$id);
                return $this->showReturnCode(1001);
            }else{
                return $this->showReturnCode(1009,'删除失败');
            }
        }else{
            return $this->showReturnCode(1002);
        }
    }

    public function merstatus()
    {
        if ($this->request->isAjax()) {
            $id = input('post.id');


            $id = model('Push')->where('id', $id)->value('mer_id');

            /*   开关开启，必须同时满足以下条件：
               1、设置定时投放后，可开启
               2、设置接收设置后，可开启
               3、设置分发规则后，可开启
            */
            if (input('post.status') == 1) {
//                $mer = Db::name('merchant')->find($id);
//                if($mer['timing'] == ''){
//                    return $this->showReturnCode(1011,'请先设置定时投放时间');
//                }

                //$mapp = Db::name('mapping')->where(['mer_id' => $id])->find();
//                if(!$mapp){
//                    return $this->showReturnCode(1011,'请先设置接收设置');
//                }

                $push = model('Push')->getListByMap(['mer_id' => $id]);
                if (!$push) {
                    return $this->showReturnCode(1011, '请先设置分发规则');
                }
            }

            $res = model('Merchant')->save(['status' => input('post.status')], ['id' => $id]);
            if ($res) {

                if (input('post.status') == 1) {
                    (new PushRecord())->addByMerchs([$id]); //判断是否需要增加分发规则生效记录
                }

                $this->RecordSystemLog($this->uid, $this->behavior, '状态操作成功,操作ID: ' . $id);
                return $this->showReturnCode(1001);
            } else {
                return $this->showReturnCode(1009, '操作失败');
            }
        } else {
            return $this->showReturnCode(1002);
        }
    }

    public function merchStatus()
    {
        if ($this->request->isAjax()) {
            $id = input('post.id');

            /*   开关开启，必须同时满足以下条件：
               1、设置定时投放后，可开启
               2、设置接收设置后，可开启
               3、设置分发规则后，可开启
            */

            $res = model('Merchant')->save(['status' => input('post.status')], ['id' => $id]);
            if ($res) {

                if (input('post.status') == 1) {
                    (new PushRecord())->addByMerchs([$id]); //判断是否需要增加分发规则生效记录
                }

                $this->RecordSystemLog($this->uid, $this->behavior, '状态操作成功,操作ID: ' . $id);
                return $this->showReturnCode(1001);
            } else {
                return $this->showReturnCode(1009, '操作失败');
            }
        } else {
            return $this->showReturnCode(1002);
        }
    }


    //批量设置开始结束时间
    public function save_timing2()
    {
        if (request()->isAjax()) {
            try {

                $id = input('post.id/a');
                $save_data = input('post.');

                if (empty($id)) {
                    return self::showReturnCode(1012, '请勾选需要设置的规则');
                }
                if ($save_data['start_time'] == '' || $save_data['end_time'] == '') {
                    return self::showReturnCode(1012, '时间不能为空');
                }

//                if(strtotime($save_data['start_time']) < time()){
//                    return self::showReturnCode(1013,'开始时间必须晚于系统时间');
//                }

                if ($save_data['start_time'] > $save_data['end_time']) {
                    return self::showReturnCode(1014, '结束时间必须晚于开始时间');
                }

                $save_data['timing'] = $save_data['start_time'] . ' - ' . $save_data['end_time'];

                foreach ($id as $v) {

                    $dbData[] = ['id' => $v, 'timing_time' => $save_data['timing'], 'start_time' => $save_data['start_time'], 'end_time' => $save_data['end_time']];
                }
                $result = model('Push')->saveAll($dbData);

                // 判断每日规则记录
                $push_record_model = new PushRecord();
                $date = date('Y-m-d H:i:s');
                if ($date < $save_data['start_time'] || $date > $save_data['end_time']) { // 不在时间段内，不存记录
                    $pushs = \db('push')->whereIn('id', $id)->select();
                    foreach ($pushs as $push) {
                        $push['timing'] = $save_data['timing'];
                        $push_record_model->editPushToRecord($push);
                    }
                }

                $this->RecordSystemLog($this->uid, $this->behavior, '规则' . implode(',', $id) . '定时投放设置成功');

                return self::showReturnCode(1001, '定时投放设置成功');
            } catch (\Exception $e) {
                Log::error($e->getMessage());
                return self::showReturnCode(1011, $e->getMessage());
            }
        } else {
            return self::showReturnCode(1002);
        }
    }

    //批量设置时段
    public function save_timeday2()
    {
        if (request()->isAjax()) {
            try {

                $id = input('post.id/a');
                $save_data = input('post.');


                if (empty($id)) {
                    return self::showReturnCode(1012, '请勾选需要设置的规则');
                }
                if ($save_data['timeday'] == '') {
                    return self::showReturnCode(1012, '时间不能为空');
                }

                $endWeek = [];
                if (!empty($save_data['wday'])) {
                    foreach ($save_data['wday'] as $v) {
                        if ($v == 10) {
                            $endWeek = [];
                            $wArr = explode(' - ', $save_data['timeday'][$v]);
                            if (count($wArr) == 2) {
                                if ($wArr[0] != $wArr[1]) {
                                    $endWeek[$v] = $save_data['timeday'][$v];
                                } else {
                                    $endWeek[$v] = '';
                                }
                            } else {
                                $endWeek[$v] = $save_data['timeday'][$v];
                            }
                            break;
                        } else {
                            $wArr = explode(' - ', $save_data['timeday'][$v]);
                            if (count($wArr) == 2) {
                                if ($wArr[0] != $wArr[1]) {
                                    $endWeek[$v] = $save_data['timeday'][$v];
                                } else {
                                    $endWeek[$v] = '';
                                }
                            } else {
                                $endWeek[$v] = $save_data['timeday'][$v];
                            }
                        }
                    }
                }

                $endWeekArr = array_keys($endWeek);
                $endWeekDay = [];
                foreach ($endWeekArr as $v) {
                    if ($v != 10) {
                        $endWeekDay[] = $v;
                    }
                }

                $endWeekDay = implode(',', $endWeekDay);

                foreach ($id as $v) {
                    $dbData[] = ['id' => $v, 'week_time' => json_encode($endWeek), 'week_day' => $endWeekDay];
                }
                $result = model('Push')->saveAll($dbData);

                // 判断每日规则记录
                $push_record_model = new PushRecord();
                // 判断接收星期几
                if (!empty($endWeek)) {
                    $weekArr = $endWeek;
                    //全部星期
                    $nowWeek = date('w');
                    if (empty($weekArr) || isset($weekArr[10]) || isset($weekArr[$nowWeek])) {
                        $pushs = \db('push')->whereIn('id', $id)->select();
                        foreach ($pushs as $push) {
                            $push['week_time'] = json_encode($endWeek);
                            $push['week_day'] = $endWeekDay;
                            $push_record_model->editPushToRecord($push);
                        }
                    }
                }

                $this->RecordSystemLog($this->uid, $this->behavior, '规则' . implode(',', $id) . '投放时段设置成功');

                return self::showReturnCode(1001, '设置成功');

            } catch (\Exception $e) {
                Log::error($e->getMessage());
                return self::showReturnCode(1011, $e->getMessage());
            }
        } else {
            return self::showReturnCode(1002);
        }
    }

    //批量设置状态
    public function multi_status()
    {
        if (request()->isAjax()) {
            try {

                $id = input('post.id/a');
                $save_data = input('post.');


                if (empty($id)) {
                    return self::showReturnCode(1012, '请勾选需要设置的规则');
                }
                if ($save_data['status'] == '') {
                    return self::showReturnCode(1012, '状态不能为空');
                }

                foreach ($id as $v) {
                    $dbData[] = ['id' => $v, 'status' => $save_data['status']];
                }
                $result = model('Push')->saveAll($dbData);

                // 判断每日规则记录
                $push_record_model = new PushRecord();
                if ($save_data['status'] == 1) {
                    $pushs = \db('push')->whereIn('id', $id)->select();
                    foreach ($pushs as $push) {
                        $push['status'] = $save_data['status'];
                        $push_record_model->editPushToRecord($push);
                    }
                }

                $this->RecordSystemLog($this->uid, $this->behavior, '规则' . implode(',', $id) . '状态设置成功');

                return self::showReturnCode(1001, '设置成功');

            } catch (\Exception $e) {
                Log::error($e->getMessage());
                return self::showReturnCode(1011, $e->getMessage());
            }
        } else {
            return self::showReturnCode(1002);
        }
    }

    //批量设置账户
    public function multi_account()
    {
        if (request()->isAjax()) {
            try {

                $id = input('post.id/a');
                $save_data = input('post.');


                if (empty($id)) {
                    return self::showReturnCode(1012, '请勾选需要设置的规则');
                }
                if (!isset($save_data['account_id']) || empty($save_data['account_id'])) {
                    return self::showReturnCode(1011, '请选择账户');
                }

                if (in_array(0, $save_data['account_id'])) {
                    $save_data['account_id'] = 0;
                    $save_data['channel_type'] = 0;
                } else {
                    // 需要构建channel_type字段：渠道id字符传
                    // 设置push表的 channel_type字段 渠道id字符传 判断是否包含渠道内所有的账户
                    $channel = \db('channel')->field('id')->where('status', 1)->select();
                    $account = \db('account')->field('channel_id,id')->where('status', 1)->select();
                    foreach ($channel as &$channel_v) {
                        $channel_v['accounts'] = [];
                        foreach ($account as &$acc_v) {
                            if ($channel_v['id'] == $acc_v['channel_id']) {
                                $channel_v['accounts'][] = $acc_v['id'];
                            }
                        }
                        unset($acc_v);
                    }
                    unset($channel_v);
                    $channel_type = $update = [];
                    foreach ($channel as $channel_acc) {
                        $intersect = array_intersect($save_data['account_id'], $channel_acc['accounts']);
                        if (array_values($channel_acc['accounts']) == array_values($intersect) && !empty($channel_acc['accounts'])) {
                            $channel_type[] = $channel_acc['id'];
                        }
                    }
                    $save_data['channel_type'] = !empty($channel_type) ? implode(",", $channel_type) : "";
                    $save_data['account_id'] = implode(',', $save_data['account_id']);
                }

                foreach ($id as $v) {
                    $dbData[] = ['id' => $v, 'account_id' => $save_data['account_id'], 'channel_type' => $save_data['channel_type']];
                }
                $result = model('Push')->saveAll($dbData);

                $this->RecordSystemLog($this->uid, $this->behavior, '规则' . implode(',', $id) . '账户设置成功');

                return self::showReturnCode(1001, '设置成功');

            } catch (\Exception $e) {
                Log::error($e->getMessage());
                return self::showReturnCode(1011, $e->getMessage());
            }
        } else {
            return self::showReturnCode(1002);
        }
    }

    public function modifyData()
    {
        if ($this->request->isAjax()) {
            $id = input('post.id');
            $save_data = input('post.');

            $push = model('Push')->where('id', $id)->find();
            if (empty($push)) {
                return $this->showReturnCode(1011, '分发规则有误');
            }
            $save_data['id'] = $id;
            $result = $this->editData(false, '', 'Push', $save_data);
            if ($result['code'] == 1001) {
                $this->RecordSystemLog($this->uid, $this->behavior, '状态操作成功,操作ID: ' . $id);
                return $this->showReturnCode(1001);
            } else {
                return $this->showReturnCode(1009, '操作失败');
            }
        } else {
            return $this->showReturnCode(1002);
        }
    }

}